package cn.chenhuanming.shh.administer.repository;

import cn.chenhuanming.shh.administer.entity.jpa.District;
import cn.chenhuanming.shh.administer.entity.jpa.Estate;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * Generated by Spring Data Generator on 25/07/2017
 */
@Repository
public interface EstateRepository extends JpaRepository<Estate, String> {

    @PreAuthorize("hasAnyRole('ROLE_INFORMATION_PUBLISHER','ROLE_ADMINISTER','ROLE_SHOP_MANAGER')")
    @Override
    Estate save(Estate estate);

    Page<Estate> findByNameContains(@Param("name") String name, Pageable pageable);

    @PreAuthorize("hasRole('ROLE_SHOP_MANAGER')")
    @Query(value = "SELECT e FROM Estate e where e.creator.username = ?#{principal.username} and e.name LIKE %:name%")
    List<Estate> findMyEstatesByNameContains(@Param("name") String name);

    @PreAuthorize("hasRole('ROLE_SHOP_MANAGER')")
    @Query(value = "SELECT e FROM Estate e where e.creator.username = ?#{principal.username} and e.name LIKE %:name%")
    Page<Estate> findMyEstatesByNameContainsPaging(@Param("name") String name, Pageable pageable);

    @Query(value = "SELECT e from Estate e where e.loop >= ?#{#loop} AND e.loop <= ?#{#loop>4||#loop==0?T(Short).parseShort(10):#loop} AND (e.district.id = ?#{#district.id} OR e.district.parent.id = ?#{#district.id}) AND e.name LIKE %?#{#name}%")
    Page<Estate> findAllThroughForeground(@Param("loop") short loop, @Param("district") District district, @Param("name") String name, Pageable pageable);

    @Query(value = "SELECT e from Estate e where e.loop >= ?#{#loop} AND e.loop <= ?#{#loop>4?10:#loop} ")
    Page<Estate> testSpelError(@Param("loop") short loop,  Pageable pageable);
}
